import type { IQuery, Response, TableResponse } from '@/api/config/types';
import { exportFile, fileUploader } from '@/api/utils/file';
import { message } from 'ant-design-vue';
import { SystemStatus } from '@/global/enum/status.enum';
import axios from 'axios';
import type { AxLang } from './types';
import type { PendingUpdates } from '@/types/system';

/**
 * @description: 统一管理API前缀，方便修改
 */
const REQUEST_PREFIX = 'ax/lang';

/**
 * @description: 查询翻译列表
 * @param {IQuery} query 系统通用查询对象
 */
export const fetchLangList = (query: IQuery) => {
  return axios.get<TableResponse<AxLang>>(`${REQUEST_PREFIX}/list`, {
    params: query,
  });
};

/**
 * @description: 查询翻译详细
 * @param {number} id 主键ID
 */
export const fetchLangById = (id: number | string) => {
  return axios.get<Response<AxLang>>(`${REQUEST_PREFIX}/${id}`);
};

/**
 * @description: 新增翻译
 * @param {AxLang} data 需要添加的数据
 */
export const createLang = (data: AxLang) => {
  return axios.post<Response<AxLang>>(`${REQUEST_PREFIX}`, data);
};

/**
 * @description: 更新翻译
 * @param {AxLang} data 更新数据
 */
export const updateLang = (data: AxLang) => {
  return axios.put<Response<AxLang>>(`${REQUEST_PREFIX}`, data);
};

/**
 * @description: 删除翻译
 * @param {number[]} ids 传入ID数组,可以删除多个
 */
export const deleteLang = (ids: (number | string)[]) => {
  return axios.delete<Response<AxLang>>(`${REQUEST_PREFIX}/${ids.join(',')}`);
};

/**
 * @description: 批量新增翻译
 * @param {AxLang[]} list
 */
export const batchCreateLang = (list: AxLang[]) => {
  return axios.post<Response>(`${REQUEST_PREFIX}/batch`, list);
};
/**
 * @description: 加载所有翻译
 */
export const loadAllLang = () => {
  return axios.get<TableResponse<AxLang>>(`${REQUEST_PREFIX}/loadAll`);
};

/**
 * @description: 导出翻译
 */
export const exportLang = async (query: IQuery) => {
  try {
    await exportFile({
      url: `${REQUEST_PREFIX}/export`,
      data: query,
      fileName: '翻译.xls',
      method: 'POST',
    });
    message.success(`成功下载`);
  } catch (e) {
    message.success(`下载失败`);
  }
};
/**
 * @description: 三向绑定 前端-后端-数据库 翻译
 */
export const updateLangAttr = (config: PendingUpdates) => {
  return axios.post<Response<AxLang>>(`${REQUEST_PREFIX}/updateAttr`, { ...config });
};

/**
 * @description: 下载模板,用于批量导入测试表
 */
export const importLang = async (file: File) => {
  try {
    const data = {
      file,
      path: file.name,
    };
    const { response } = await fileUploader({
      files: [data],
      url: `${REQUEST_PREFIX}/importData`,
    });
    if (response.code === SystemStatus.SUCCESS) {
      message.success('上传成功');
    }
  } catch (e) {
    message.success(`上传失败`);
  }
};

type Translation = {
  text: string;
  sourceLanguage: string;
  targetLanguage: string;
};

interface TranslationResponse {
  translated: string;
  lang: string;
}
export const translationText = (data: Translation[]) => {
  return axios.post<Response<TranslationResponse[]>>(`${REQUEST_PREFIX}/translation`, data);
};
